<template>
  <Card>
    <div class="inline-form">
      <!-- 表单内容 -->
      <Form ref="formValdate" :model="formValdate" :rules="ruleValdate" :label-width="100" style="display: block;">

        <!-- <FormItem prop="yearMonth" label=""> -->
        <!-- <el-radio-group v-model="formValdate.resource" class="group-top">
          <el-radio label="1">渠道</el-radio>
          <el-radio label="2">业务员</el-radio>
        </el-radio-group> -->
        <!-- </FormItem> -->
        <FormItem prop="yearMonth" label="品质年月:">
          <DatePicker type="month" v-model="formValdate.yearMonth" class="form-input-small" placeholder="请选择"
            @on-change="dateChange" :options="dateOptions" style="width: 300px;"></DatePicker>
        </FormItem>
        <FormItem label="渠道名称:" prop="managecome">
          <el-select v-model="formValdate.managecome" placeholder="渠道" style="width: 300px;">
            <el-option v-for="item in aaMa" :key="item.key" :label="item.value" :value="item.key">
            </el-option>
          </el-select>
          <!-- <Cascader change-on-select :data="managecomeList" v-model="formValdate.managecome"
            @on-change="organizationChange" placeholder="请选择" clearable style="width: 300px;"></Cascader> -->
        </FormItem>
        <!-- <FormItem v-if="formValdate.resource == 2" label="续期专员:" prop="reagentCode">
          <Select v-model="formValdate.reagentCode" placeholder="请选择" style="width: 300px;">
            <Option v-for="item in reagentCodeListM" :key="item.key" :value="item.key">{{ item.value }}-{{ item.key }}
            </Option>
          </Select>
        </FormItem> -->
        <FormItem label="品质类型:" prop="scoreType">
          <Select v-model="formValdate.scoreType" placeholder="请选择" style="width: 300px;">
            <Option v-for="item in scoreTypeList" :key="item.key" :value="item.key">{{ item.value }}</Option>
          </Select>
        </FormItem>
        <FormItem label="调整情况:" prop="revision">
          <Select v-model="formValdate.revision" placeholder="请选择" style="width: 300px;">
            <Option v-for="item in [{ value: '升级', key: '1' }, { value: '降级', key: '2' }]" :key="item.key"
              :value="item.key">{{ item.value }}</Option>
          </Select>
        </FormItem>
        <!-- <el-radio-group v-model="formValdate.resource"> -->
        <div class="group-top">
          <el-radio value="1" label="1" style="margin-right:10px;">{{ formValdate.revision == 1 ? '升' : '降' }}
          </el-radio>
          <Select v-model="formValdate.aaaa" placeholder="请选择" style="width:100px;margin-right:55px;">
            <Option v-for="item in changeLevelList" :key="item" :value="item">{{ item }}</Option>
          </Select>
          <el-radio value="2" label="2" style="margin-right:10px;">{{ formValdate.revision == 1 ? '升至' : '降至'
          }}</el-radio>
          <Select v-model="formValdate.bbbb" placeholder="请选择" style="width:100px;margin-right:30px;">
            <Option v-for="item in levelList" :key="item" :value="item">{{ item }}</Option>
          </Select>
        </div>
        <!-- </el-radio-group> -->
        <!-- <FormItem prop="addsubScore" label="品质加扣分:">
          <Input type="text" v-model="formValdate.addsubScore" placeholder="请输入品质加扣分" />
        </FormItem> -->
        <FormItem label="详情:" prop="detail">
          <Input v-model="formValdate.detail" type="textarea" :autsoize="{ minRows: 10, maxRows: 15 }" placeholder="请输入"
            style="width: 300px;" />
        </FormItem>
        <FormItem prop="leaveFile" label="附件:">
          <Uploadv multiple ref="upload" type="drag" :format="['pdf', 'mp4']" :on-format-error="handleFormatError"
            :before-upload="handleUpload" :show-upload-list="false" :on-success="uploadSuccess" :on-error="uploadFail"
            :headers="{ Authorization: tocken, }" name="multipartFile" :data="{ applyNo: '1' }" :action="action"
            style="width: 300px;">
            <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
            <p>点击或将文件拖拽到这里上传</p>
            <p style="color:rgba(0,0,0,0.43)">支持扩展名：.pdf和.mp4</p>
          </Uploadv>
          <div v-for="(item, index) in file" :key="index">
            <div>
              <Icon type="md-attach" style="transform:rotate(90deg);" />
              &nbsp;{{ item.name }}
              <span @click="delectFile(item.keyID)" class="deleteFile">X</span>
            </div>
          </div>
        </FormItem>
        <FormItem>
          <div style="width: 300px;text-align: center;">
            <Button type="default" @click="$router.go(-1)" style="width:74px;margin-right:50px">返回</Button>
            <Button type="primary" style="width:74px;" @click="handleSubmit(formValdate)"
              :loading="submitLoading">提交</Button>
          </div>
        </FormItem>
      </Form>
    </div>
    <Button type="primary" @click="info" v-if="false"></Button>
  </Card>
</template>


<script>
export default {
  data() {
    const validateScore = (rule, value, callback) => {
      let scopeReg = /^(-)?[1-9][0-9]*$/;
      if (!scopeReg.test(value)) {
        callback(new Error("必须输入正整数或负整数"));
      } else {
        callback();
      }
    };
    return {
      formValdate: {
        managecome: [],
        reagentCode: "",
        scoreType: "",
        yearMonth: "",
        addsubScore: "",
        resource: '1',
        revision: '1',
        detail: ''
      },
      managecomeList: [],
      reagentCodeList: [],
      scoreTypeList: [],
      levelList: ['AAA级', 'AA级', 'A级', 'BBB级', 'BB级', 'B级', 'CCC级', 'CC级', 'C级', 'D级',],
      changeLevelList: ['1级', '2级', '3级', '4级', '5级', '6级', '7级', '8级', '9级', '10级',],
      ruleValdate: {
        managecome: [{ required: true, message: "渠道不能为空" }],
        reagentCode: [{ required: true, message: "续期专员不能为空" }],
        scoreType: [{ required: true, message: "品质类型不能为空" }],
        yearMonth: [{ required: true, message: "品质年月不能为空" }],
        reagentCode: [{ required: true, message: "续期专员不能为空" }],
        revision: [{ required: true, message: "调整情况不能为空" }],
        detail: [{ required: true, message: "详情不能为空", trigger: "blur" }],
        addsubScore: [
          { required: true, message: "品质加扣分不能为空" },
          { validator: validateScore, trigger: "blur" },
          { validator: validateScore, trigger: "change" }
        ]
      },
      submitLoading: false,
      tocken: null,
      file: [],
      delectFiles: [],
      action: '',
      fileIndex: 0,
      fileFlag: 0,
      dateOptions: {
        disabledDate(date) {
          var d = new Date();
          d.setMonth(d.getMonth() + 3);
          var yy1 = d.getFullYear();
          var mm1 = d.getMonth() + 1;
          var dd1 = d.getDate();
          if (mm1 < 10) {
            mm1 = "0" + mm1;
          }
          if (dd1 < 10) {
            dd1 = "0" + dd1;
          }
          var today = new Date();
          return (
            date &&
            (date.valueOf() > Date.parse(yy1 + "-" + mm1 + "-" + dd1) ||
              date.valueOf() <
              Date.parse(today.getFullYear() + "-" + (today.getMonth() + 1)))
          );
        }
      }
    };
  },
  methods: {
    info(tip) {
      this.$Message.info(tip);
    },
    // 更改时间
    dateChange(e) {
      if (this.formValdate.yearMonth) {
        this.formValdate.yearMonth = e.substr(0, 4) + "-" + e.substr(5, 7);
      }
    },
    // 获取续期专员机构下拉框信息
    getAllOrganization() {
      // 续期机构下拉框
      // this.api.selectUerList().then(res => {
      //   if (res.code == 200 && res.data != null) {
      //     this.managecomeList = res.data[0].listKeyValueVOS;
      //   } else {
      //     this.managecomeList = [];
      //   }
      // });
      this.api.remanagecomList().then(res => {
        if (res.code == 200 && res.data != null) {
          let arr = []
          arr.push(res.data)
          arr.forEach(one => {
            one.value = one.comcode
            one.label = one.comcode + '-' + one.name
            one.children = one.chilDren || []
            if (one.children) {
              one.chilDren.forEach(two => {
                two.value = two.comcode
                two.label = two.comcode + '-' + two.name
                two.children = two.chilDren || []
                if (two.children) {
                  two.children.forEach(three => {
                    three.value = three.comcode
                    three.label = three.comcode + '-' + three.name
                    three.children = three.chilDren || []
                    if (three.children) {
                      three.children.forEach(four => {
                        four.value = four.comcode
                        four.label = four.comcode + '-' + four.name
                        four.children = four.chilDren || []
                      })
                    }
                  })
                }
              })
            }
          })
          console.log(arr);
          this.managecomeList = arr
        } else {
          this.managecomeList = [];
        }
      });
    },
    // 获取续期专员姓名下拉框信息
    organizationChange(value) {
      if (!value) {
        this.reagentCodeList = [];
      } else {
        this.api.selectXQCode({ managecom: value[value.length - 1] }).then(res => {
          if (res.code == 200) {
            if (res.data) {
              this.reagentCodeList = res.data;
            } else {
              this.reagentCodeList = [];
            }
            // console.log(res);
          } else {
            this.reagentCodeList = [];
            this.$Message.info(res.msg);
          }
        });
      }
    },
    // 品质类型下拉框
    getQualityType() {
      this.api.getQualityType().then(res => {
        if (res.code == 200) {
          this.scoreTypeList = res.data;
        }
      });
    },
    // 查询
    handleSubmit() {
      console.log('formValdate.managecome', this.formValdate.managecome);
      this.$refs.formValdate.validate(valid => {
        if (valid) {
          this.submitLoading = true;
          let obj = {
            managecom: this.formValdate.managecome[this.formValdate.managecome.length - 1],
            reagentCode: this.formValdate.reagentCode,
            scoreType: this.formValdate.scoreType,
            yearMonth: this.formValdate.yearMonth,
            addsubScore: this.formValdate.addsubScore,
            detail: this.formValdate.detail
          };
          // console.log(this.delectFiles,this.file,obj);
          // 删除文件
          if (this.deleteFiles) {
            this.deleteFiles.forEach(element => {
              if (element.id) {
                let obj = {
                  id: element.id
                };
                this.api.deleteAttachment(obj).then(res => {
                  if (res.code == 200) {
                  } else {
                    this.info(res.msg);
                    return false;
                  }
                });
              }
            });
          }
          this.$router.go(-1);
          this.info("品质录入提交成功!");
          // console.log(obj);
          // this.api.addUerQualityEntering(obj).then(res => {
          //   if (res.code == 200 && res.data != null) {
          //     if (res.data) {
          //       this.$refs.upload.applyNo = res.data;
          //     } else {
          //       this.info("文件上传失败");
          //     }
          //     this.upload();
          //   } else {
          //     this.submitLoading = false;
          //     this.info(res.msg);
          //   }
          // });
        } else {
          this.info("信息填写有误");
        }
      });
    },
    handleReset() {
      this.submitLoading = false;
      this.$refs.formValdate.resetFields();
      this.formValdate.detail = null;
      this.file = [];
    },
    handleFormatError() {
      this.info("只能上传pdf和mp4格式的文件！");
    },
    // 保存需要上传的文件
    handleUpload(file) {
      let hz = file.name.split(".");
      if (hz[1] == "pdf" || hz[1] == "mp4") {
        let keyID = Math.random()
          .toString()
          .substr(2);
        // 16位前端标志id
        file["keyID"] = keyID;
        this.file.push(file);
        return false;
      }
    },
    // 删除文件
    delectFile(keyID) {
      this.file = this.file.filter(item => {
        if (item.keyID == keyID) {
          // 保存到删除文件数组
          if (item.id) {
            this.deleteFiles.push(item);
          }
        }
        return item.keyID != keyID;
      });
    },

    // 上传文件
    upload() {
      if (this.file.length > 0) {
        for (let i = 0; i < this.file.length; i++) {
          let item = this.file[i];
          // 重新提交原文件不上传
          if (item.id) {
            this.fileIndex++;
            // 如果全部是原文件
            if (this.fileIndex == this.file.length) {
              this.submitLoading = false;
              this.info("品质录入提交成功！");
              this.file = [];
              this.$refs.formValdate.resetFields();
              this.formValdate.detail = null;
            }
          } else {
            this.$refs.upload.post(item);
          }
        }
      } else {
        this.submitLoading = false;
        this.$refs.formValdate.resetFields();
        this.formValdate.detail = null;
        // this.$refs.formValdate.resetFields();
        this.$router.push({
          path: "qualityRecord"
        });
        this.info("品质录入提交成功！");
      }
    },

    // 文件上传成功
    uploadSuccess(response, file, fileList) {
      this.fileIndex++;
      this.$Message.info(response.data[0].name + "上传成功");
      if (this.fileIndex == this.file.length) {
        this.submitLoading = false;
        this.file = [];
        this.$refs.formValdate.resetFields();
        this.formValdate.detail = null;
        this.$router.push({
          path: "qualityRecord"
        });
        this.info("品质录入提交成功!");
      }
      return true;
    },

    // 文件上传失败
    uploadFail(response, file, fileList) {
      // console.log(response, file, fileList);
      this.fileIndex++;
      this.info(fileList.name + "上传失败");
      if (this.fileIndex == this.file.length) {
        this.submitLoading = false;
        this.file = [];
        this.info("品质录入提交失败！");
      }
      return false;
    }
  },
  mounted() {
    this.getAllOrganization();
    this.getQualityType();
    this.tocken = sessionStorage.getItem("credentials");
    // this.action = sessionStorage.getItem("userIp") + "scrm-uer/api/fileupload/up";
    this.action = "/scrm-gateway/scrm-uer/api/fileupload/up";
    // this.action = "http://192.168.137.184:8881/api/fileupload/up";
  }
};
</script>


<style lang="less" scoped>
@import "./record";

.group-top::before {
  content: '*';
  display: inline-block;
  margin-right: 4px;
  line-height: 1;
  font-family: SimSun;
  font-size: 14px;
  color: #ff0000;
  margin-right: 10px;
}

.group-top {
  margin-bottom: 24px;
  margin-left: 16px;
}
</style>

<style>
textarea.ivu-input {
  resize: none;
}
</style>